//
//  XMLParser.m
//  HelloWorld
//
//  Created by Beomjun Kim on 09. 08. 25.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "XMLParser.h"


@implementation XMLParser
@synthesize root;
@synthesize stack;

// Public parser returns the tree root
- (TreeNode *)parseXMLFile: (NSURL *) url
{
	// Create a new clean stack
	self.stack = [[[NSMutableArray alloc] init] autorelease];
	
	// Initialize the root
	self.root = [[[TreeNode alloc] init] autorelease];
	self.root.parent = NULL;
	self.root.leafvalue = NULL;
	self.root.children = [[[NSMutableArray alloc] init] autorelease];
	[self.stack addObject:self.root];
	
	// Parse the incoming data
    NSXMLParser *parser = [[[NSXMLParser alloc] initWithContentsOfURL:url] autorelease];
    [parser setDelegate:self];
	[parser parse];
	
	// pop down to real root
	return [self.root.children lastObject];
}

- (void) dealloc
{
	if (self.stack) [self.stack release];
	if (self.root) [self.root release];
	[super dealloc];
}

// Descend to a new element
- (void)parser:(NSXMLParser *)parser 
		didStartElement:(NSString *)elementName 
		namespaceURI:(NSString *)namespaceURI 
		qualifiedName:(NSString *)qName 
		attributes:(NSDictionary *)attributeDict
{
	TreeNode *leaf = [[[TreeNode alloc] init] autorelease];
	leaf.parent = [stack lastObject];
	[leaf.parent.children addObject:leaf];
	[self.stack addObject:leaf];
	
	leaf.key = qName ? qName : elementName;
	
	// 아래부분에 release가 잘못되어 있는 것 같다.
	//[qName ? qName : elementName release];
	
	leaf.leafvalue = NULL;
	leaf.children = [[[NSMutableArray alloc] init] autorelease];
	
}

// Pop after finishing element
- (void)parser:(NSXMLParser *)parser 
		didEndElement:(NSString *)elementName 
		namespaceURI:(NSString *)namespaceURI 
		qualifiedName:(NSString *)qName
{
	[self.stack removeLastObject];
}

// Reached a leaf
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
	if (![[self.stack lastObject] leafvalue])
	{
		[[self.stack lastObject] setLeafvalue:string];
		return;
	}
	[[self.stack lastObject] setLeafvalue:[NSString stringWithFormat:@"%@%@", [[self.stack lastObject] leafvalue], string]];
}
@end
